package concurrent;

import java.time.LocalTime;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author Summerday
 */
public class BlockingQueueDemo {

    // 创建一个长度为容量为1的 ArrayBlockingQueue
    static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("此时队列中没有元素");
        Thread A = new Thread(() -> {
            // 此时队列为空,take为阻塞获取,如果获取不到元素,将会一直阻塞
            Integer take = null;
            try {
                System.out.println(LocalTime.now() + " A试图获取元素, 但是陷入阻塞..");
                take = queue.take();
                System.out.println(LocalTime.now() + " A成功获取元素 " + take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A");

        Thread B = new Thread(() -> {
            try {
                queue.put(520);
                System.out.println(LocalTime.now() + " B 向队列中加入元素...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "V");

        Thread C = new Thread(() -> {
            try {
                System.out.println(LocalTime.now() + " C也尝试从空的队列中获取元素,但是3s取不到,就退出阻塞");
                Integer poll = queue.poll(3, TimeUnit.SECONDS);
                System.out.println(LocalTime.now() + " C获取到元素" + poll);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "V");
        A.start();
        C.start();
        // 主线程睡5s,5s之后B再向队列中加元素
        Thread.sleep(5000);
        B.start();
    }
}
